﻿String.format = function (text) {
    if (arguments.length <= 1) {
        return text;
    }
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }
    return text;
};


//SETTINGs
var sohaEmbed_SourceDomain = "http://soha.vn";
var sohaEmbed_CafeF_CssSource = "/www/cafef/cafef-style.css";
var sohaEmbed_CafeF_utmSource = "?utm_source=CafeF&utm_medium=CafeFEmbed&utm_campaign=CafeFBoxEmbed";
var sohaEmbed_CafeF_headUtmSource = "?utm_source=CafeF&utm_medium=Head_CafeFEmbed&utm_campaign=Head_CafeFBoxEmbed";
var sohaEmbed_CafeF_BoxID = "sohaEmbed_CafeF";
//

var vSohaEmbed = new function () {

    this.imageWidth = 96;
    this.imageHeight = 71;
    this.top = 28;
    this.type = 1;

    this.sohaSlideWrapper = "vSohaSlideWrapper";



    //BIND DATA
    vSoha_bindData = function (data) {
        data = eval('(' + data + ')');
        if (data != null && data.length > 0) {
            var embedHtml = '';
            var format = "<li class=\"{4}\"><a href=\"{0}\" target=\"_blank\" title=\"{2}\">{3}<p>{1}</p></a></li>";
            var firstCssClass = "vsohaEmbed_mgt10";
            var cssClass = "vsohaEmbed_mgt14";
            var numberOfLi = 6;

            for (var i = 0; i < data.length; i++) {

                var item = data[i];
                if (i % numberOfLi == 0) {
                    embedHtml += "<ul class=\"vsohaEmbed_box-sohact\">";
                }

                embedHtml += String.format(
                        format,
                        item["AbsoluteURL"] + sohaEmbed_CafeF_utmSource,
                        item["Title"],
                        item["EncodedTitle"],
                        item["FormatedImage"],
                        i == 0 ? firstCssClass : cssClass);


                if (((i + 1) % numberOfLi) == 0 || (i + 1) == data.length) {
                    embedHtml += "</ul>";
                }

            }

            $("#vSohaSlideWrapper").html(embedHtml);
            $("#" + sohaEmbed_CafeF_BoxID).show();
            $("#" + sohaEmbed_CafeF_BoxID + " a:not('.rowsprite')").attr("target", "_blank");
            var cssSourceFormat = "<link href=\"{0}{1}\" rel=\"stylesheet\" type=\"text/css\" />";
            $("head").append(String.format(cssSourceFormat, sohaEmbed_SourceDomain, sohaEmbed_CafeF_CssSource));
        }
    };


    //GET DATA 
    this.vSoha_getData = function () {
        var urlFormat = "/Services/GetEmbedData.ashx?Top={0}&ImageWidth={1}&ImageHeight={2}&Type={3}";

        var url = sohaEmbed_SourceDomain + String.format(urlFormat, this.top, this.imageWidth, this.imageHeight, this.type);
        var ohtml = '';
        ohtml += "<div id=\"" + sohaEmbed_CafeF_BoxID + "\" class=\"vsohaEmbed_box-soha\">";
        ohtml += "<a href=\"http://soha.vn" + sohaEmbed_CafeF_headUtmSource + "\" class=\"vsohaEmbed_box-sohatt\">TIN HOT TỪ SOHA.VN</a>";
        ohtml += "<div id=\"vSohaSlideWrapper\">";
        ohtml += "</div>";
        ohtml += "<div class=\"vsohaEmbed_boxsh-row\">";
        ohtml += "<a href=\"javascript:void(0);\" id=\"vSohaEmbed_btnPre\" class=\"vsohaEmbed_prebt rowsprite\"></a><a href=\"javascript:void(0);\" id=\"vSohaEmbed_btnNext\" class=\"vsohaEmbed_nextbt-active rowsprite\"></a>";
        ohtml += "<p id=\"vSohaEmbed_SlideCounter\">";
        ohtml += "</p>";
        ohtml += "</div>";
        ohtml += "</div>";
        document.write(ohtml);
        $("#" + sohaEmbed_CafeF_BoxID).hide();
        $.ajax({
            type: 'GET',
            url: url,
            dataType: "jsonp",
            success: function (response) {
                if (JSON.stringify(response.Success)) {
                    vSoha_bindData(JSON.stringify(response.Data));
                    vSoha_makeItSlideable();
                }
            },
            error: function (e) {
                console.log(JSON.stringify(e));
            }
        });
    }


    //MAKE IT SLIDE
    var vSoha_makeItSlideable = function () {

        var currentPosition = 0;
        var slideWidth = 293;
        var displayNum = 1;
        var speed = 8000;


        var slides = $(".vsohaEmbed_box-sohact");


        if (slides.length > 0) {
            var numberOfSlides = slides.length;
            var numberOfDisplay = Math.ceil(numberOfSlides / displayNum);

            slides.hide();


            //slides.wrapAll("<div id='sohaSlideWrapper'></div>");
            var slideWrapper = $("#vSohaSlideWrapper");
            slideWrapper.css({
                "width": numberOfSlides * slideWidth + "px",
                "float": "left",
                "position": "relative"
            });

            slideWrapper.wrapAll("<div id='vSohaViewPort'></div>");
            var viewPort = $("#vSohaViewPort");
            viewPort.css({
                "width": slideWidth + "px",
                "float": "left",
                "position": "relative",
                "overflow": "hidden"
            });

            slides.show();

            var lis = viewPort.find("li");
            var numberOfLi = 6;
            var counterFormat = " {0} - {1} / {2}";

            function changePosition() {
                if (currentPosition == numberOfDisplay - 1) {
                    currentPosition = 0;
                } else {
                    currentPosition++;
                }
                moveSlide();
            }

            function setCouterStatus() {
                $("#vSohaEmbed_SlideCounter").html(String.format(
                            counterFormat,
                            currentPosition * numberOfLi + 1,
                            ((currentPosition + 1) * numberOfLi) <= lis.length ? ((currentPosition + 1) * numberOfLi) : lis.length,
                            lis.length
                        ));
            }

            function moveSlide() {
                slideWrapper.animate({ 'marginLeft': slideWidth * displayNum * (-currentPosition) });
                //console.log("currentpos: " + currentPosition + ", numberOfDisplay: " + numberOfDisplay + ", numberOfLi " + numberOfLi);
                setCouterStatus();
            }

            function changePositionToLeft() {

                if (currentPosition <= 0) {
                    currentPosition = numberOfDisplay - 1;
                } else {
                    currentPosition--;
                }
                moveSlide();
            }

            var sohaEmbedInterval = setInterval(changePosition, speed);

            $('.vsohaEmbed_box-sohact').hover(
                function () {
                    clearInterval(sohaEmbedInterval);
                },
                function () {
                    sohaEmbedInterval = setInterval(changePosition, speed);
                }
            );


            $('#vSohaEmbed_btnNext').hover(
                        function () {
                            clearInterval(sohaEmbedInterval);
                            $(this).bind('click', changePosition);
                        },
                        function () {
                            $(this).unbind('click');
                            sohaEmbedInterval = setInterval(changePosition, speed);
                        }
                    );

            $('#vSohaEmbed_btnPre').hover(
                        function () {
                            clearInterval(sohaEmbedInterval);
                            $(this).bind('click', changePositionToLeft);
                        },
                        function () {
                            $(this).unbind('click');
                            sohaEmbedInterval = setInterval(changePosition, speed);
                        }
                    );

            setCouterStatus();
        }

    }
};


vSohaEmbed.vSoha_getData();
     